import moment from 'dayjs'

function money(value, number) {
	if (!value) return '0.00';
	var value = value.toFixed(number);//提前保留两位小数
	var intPart = Number(value).toFixed(0); // 获取整数部分
	var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); // 将整数部分逢三一断 ？？？
	var floatPart = '.00'; // 预定义小数部分
	value = value.toString();//将number类型转为字符串类型，方便操作

	var value2Array = value.split('.');
	if (value2Array.length === 2) { // =2表示数据有小数位
	  floatPart = value2Array[1].toString(); // 拿到小数部分
	  if (floatPart.length === 1) { // 补0,实际上用不着
		  return intPartFormat;
	  } else {
		  return intPartFormat + '.' + floatPart;
	  }
	} else {
	  return intPartFormat;
	}
}
function timeFrom(dateTime = null, format = 'yyyy-mm-dd') {
	var format = format || 'yyyy-mm-dd'
	var timestamp = Number(Date.parse(dateTime))

	let timer = (Number(new Date()) - timestamp) / 1000;
	// 如果小于5分钟,则返回"刚刚",其他以此类推
	// console.log(timer,'----')
	let tips = '';
	switch (true) {
		case timer < 300:
			tips = '刚刚';
			break;
		case timer >= 300 && timer < 3600:
			tips = parseInt(timer / 60) + '分钟前';
			break;
		case timer >= 3600 && timer < 86400:
			tips = parseInt(timer / 3600) + '小时前';
			break;
		case timer >= 86400 && timer < 86400*3:
			tips = parseInt(timer / 86400) + '天前';
			break;
		default:
			// 如果format为false，则无论什么时间戳，都显示xx之前
			if(format === false) {
				if(timer >= 2592000 && timer < 365 * 86400) {
					tips = parseInt(timer / (86400 * 30)) + '个月前';
				} else {
					tips = parseInt(timer / (86400 * 365)) + '年前';
				}
			} else {
				tips = moment(dateTime).format('YYYY-MM-DD')
			}
	}
	return tips;
}

function YMD(date) {
	return moment(date).format('YYYY-MM-DD')
}
function subYMD(val) {
	if (val == null || val == undefined) {
	  return '';
	}
	return val.substring(0, 10);
}
 /**
  * 金钱单位置换  2999 --> 2,999.00
  * @param val
  * @param unit
  * @param location
  * @returns {*}
  */
function unitPrice(val, unit, location) {
 	
   if (!val) val = 0;
   let price = formatPrice(val);
   if (location === "before") {
     return price.substr(0, price.length - 3);
   }
   if (location === "after") {
     return price.substr(-2);
   }
   return (unit || "") + price;
 }
 /**
  * 货币格式化
  * @param price
  * @returns {string}
  */
function formatPrice(price) {
   if (typeof price !== "number") return price;
   return String(Number(price).toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
 }
  
export default{ money ,YMD,subYMD,timeFrom,unitPrice}